/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.mall.cart.cmd.storeOrder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.core.factory.Java110TransactionalFactory;
import com.java110.dto.app.AppDto;
import com.java110.dto.storeOrder.StoreCartDto;
import com.java110.dto.storeOrder.StoreOrderCartDto;
import com.java110.dto.storeOrder.StoreOrderDto;
import com.java110.dto.user.UserAddressDto;
import com.java110.intf.cart.IStoreCartV1InnerServiceSMO;
import com.java110.intf.cart.IStoreOrderAddressV1InnerServiceSMO;
import com.java110.intf.cart.IStoreOrderCartV1InnerServiceSMO;
import com.java110.intf.cart.IStoreOrderV1InnerServiceSMO;
import com.java110.intf.dev.IAppV1InnerServiceSMO;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.intf.user.IUserAddressInnerServiceSMO;
import com.java110.po.storeOrder.StoreCartPo;
import com.java110.po.storeOrder.StoreOrderAddressPo;
import com.java110.po.storeOrder.StoreOrderCartPo;
import com.java110.po.storeOrder.StoreOrderPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 类表述：保存
 * 服务编码：storeOrder.saveStoreOrder
 * 请求路劲：/app/storeOrder.SaveStoreOrder
 * add by 吴学文 at 2023-08-21 17:24:57 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网：http://www.homecommunity.cn
 * 温馨提示：如果您对此文件进行修改 请不要删除原有作者及注释信息，请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复，注释10至20行 加入 20行至30行
 */
@Java110Cmd(serviceCode = "storeOrder.saveStoreOrder")
public class SaveStoreOrderCmd extends Cmd {

    private static Logger logger = LoggerFactory.getLogger(SaveStoreOrderCmd.class);

    public static final String CODE_PREFIX_ID = "10";

    @Autowired
    private IStoreOrderV1InnerServiceSMO storeOrderV1InnerServiceSMOImpl;

    @Autowired
    private IStoreOrderAddressV1InnerServiceSMO storeOrderAddressV1InnerServiceSMOImpl;

    @Autowired
    private IStoreOrderCartV1InnerServiceSMO storeOrderCartV1InnerServiceSMOImpl;

    @Autowired
    private IStoreCartV1InnerServiceSMO storeCartV1InnerServiceSMOImpl;

    @Autowired
    private IAppV1InnerServiceSMO appV1InnerServiceSMOImpl;

    @Autowired
    private IUserAddressInnerServiceSMO userAddressInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "payType", "请求报文中未包含payType");
        Assert.hasKeyAndValue(reqJson, "deliveryType", "请求报文中未包含deliveryType");
        Assert.hasKeyAndValue(reqJson, "addressId", "请求报文中未包含addressId");
        Assert.hasKey(reqJson, "products", "请求报文中未包含商品信息");
        Assert.hasKey(reqJson, "shopId", "未包含商铺ID");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        String userId = cmdDataFlowContext.getReqHeaders().get("user-id");
        String appId = cmdDataFlowContext.getReqHeaders().get("app-id");
        AppDto appDto = new AppDto();
        appDto.setAppId(appId);
        List<AppDto> appDtos  = appV1InnerServiceSMOImpl.queryApps(appDto);
        Assert.listOnlyOne(appDtos, "应用不存在");

        JSONArray products = reqJson.getJSONArray("products");
        if (products.size() < 1) {
            throw new IllegalArgumentException("请求报文中未包含订单商品信息");
        }
        JSONObject _pro = null;
        List<StoreCartDto> storeCartDtos = new ArrayList<>();
        for (int index = 0; index < products.size(); index++) {
            _pro = products.getJSONObject(index);
            StoreCartDto storeCartDto = BeanConvertUtil.covertBean(_pro, StoreCartDto.class);
            List<StoreCartDto> _storeCartDtos = storeCartV1InnerServiceSMOImpl.queryStoreCarts(storeCartDto);
            if (_storeCartDtos.size() == 1){
                storeCartDtos.addAll(_storeCartDtos);
            }else{
                throw new IllegalArgumentException("请求报文中订单单个商品信息有误");
            }
        }
        if (storeCartDtos.size() == 0){
            throw new IllegalArgumentException("请求报文订单商品信息有误");
        }
        UserAddressDto userAddressDto = new UserAddressDto();
        userAddressDto.setAddressId(reqJson.getString("addressId"));
        List<UserAddressDto> userAddressDtos =  userAddressInnerServiceSMOImpl.queryUserAddresss(userAddressDto);
        if (userAddressDtos.size() < 1) {
            throw new IllegalArgumentException("请求报文中收货地址异常");
        }
        //1，创建订单信息
        StoreOrderPo storeOrderPo = BeanConvertUtil.covertBean(reqJson, StoreOrderPo.class);
        storeOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        BigDecimal totalPrice = new BigDecimal(0.0);
        String _remark ="";
        int flag = 0;
        //2，创建订单商品信息
        for (StoreCartDto _cart : storeCartDtos){
            BigDecimal storeOrderCartPrice = new BigDecimal(Double.parseDouble(_cart.getPrice()));
            storeOrderCartPrice = storeOrderCartPrice.multiply(new BigDecimal(_cart.getCartNum()));
            StoreOrderCartPo storeOrderCartPo = new StoreOrderCartPo() ;
            storeOrderCartPo.setCartId(_cart.getCartId());
            storeOrderCartPo.setOrderId(storeOrderPo.getOrderId());
            storeOrderCartPo.setProductId(_cart.getProductId());
            storeOrderCartPo.setValueId(_cart.getValueId());
            storeOrderCartPo.setStoreId(_cart.getStoreId());
            storeOrderCartPo.setPersonId(userId);
            storeOrderCartPo.setCartNum(_cart.getCartNum());
            storeOrderCartPo.setPrice(_cart.getPrice());
            storeOrderCartPo.setPayPrice(storeOrderCartPrice.doubleValue() + "");
            storeOrderCartPo.setFreightPrice("0.00");
            storeOrderCartPo.setState(StoreOrderCartDto.STATE_WAIT_SERV_WAIT_PAY);
            storeOrderCartPo.setProdName(_cart.getProdName());
            storeOrderCartPo.setShopId(_cart.getShopId());
            flag = storeOrderCartV1InnerServiceSMOImpl.saveStoreOrderCart(storeOrderCartPo);
            if (flag < 1) {
                throw new CmdException("保存商品详情失败");
            }
            totalPrice = totalPrice.add(storeOrderCartPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
            _remark += _cart.getProdName()+"："+_cart.getCartNum()+"*"+_cart.getPrice()+"；";
        }
        storeOrderPo.setoId(StringUtil.isEmpty(Java110TransactionalFactory.getOId()) ? "-1" : Java110TransactionalFactory.getOId());
        storeOrderPo.setPersonId(userId);
        storeOrderPo.setPersonName(userAddressDtos.get(0).getUsername());
        storeOrderPo.setTotalPrice(totalPrice.doubleValue() + "");
        storeOrderPo.setPayPrice(totalPrice.doubleValue() + "");
        storeOrderPo.setFreightPrice("0");
        storeOrderPo.setState(StoreOrderDto.STATE_WAIT_PAY);//待支付
        storeOrderPo.setRemark(_remark);
        storeOrderPo.setAppId(appDtos.get(0).getAppId());
        storeOrderPo.setAppName(appDtos.get(0).getName());
        storeOrderPo.setProfitSharing(StoreOrderDto.PROFIT_SHARING_NO);
        storeOrderPo.setShopId(reqJson.getString("shopId"));
        flag = storeOrderV1InnerServiceSMOImpl.saveStoreOrder(storeOrderPo);
        if (flag < 1) {
            throw new CmdException("生成订单失败");
        }
        //3，保存收货地址
        StoreOrderAddressPo storeOrderAddressPo = new StoreOrderAddressPo();
        storeOrderAddressPo.setOaId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        storeOrderAddressPo.setAddress(userAddressDtos.get(0).getAreaName()+userAddressDtos.get(0).getAddress());
        storeOrderAddressPo.setAddressId(userAddressDtos.get(0).getAddressId());
        storeOrderAddressPo.setOrderId(storeOrderPo.getOrderId());
        storeOrderAddressPo.setAreaCode(userAddressDtos.get(0).getAreaCode());
        storeOrderAddressPo.setUsername(userAddressDtos.get(0).getUsername());
        storeOrderAddressPo.setTel(userAddressDtos.get(0).getTel());
        flag = storeOrderAddressV1InnerServiceSMOImpl.saveStoreOrderAddress(storeOrderAddressPo);
        if (flag < 1) {
            throw new CmdException("保存订单收货地址失败");
        }
        //4,删除购物车商品信息
        for (StoreCartDto _cart : storeCartDtos){
            StoreCartPo storeCartPo = new StoreCartPo();
            storeCartPo.setCartId(_cart.getCartId());
            flag = storeCartV1InnerServiceSMOImpl.deleteStoreCart(storeCartPo);
            if (flag < 1) {
                throw new CmdException("删除购物车物品失败");
            }
        }
        ResultVo resultVo = new ResultVo(storeOrderPo);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(resultVo.toString(), HttpStatus.OK);
        cmdDataFlowContext.setResponseEntity(responseEntity);
    }
}
